# qq496631085 xiaohe
from fastapi import FastAPI
# 按 Shift+F10 执行或将其替换为您的代码。
# 按 双击 Shift 在所有地方搜索类、文件、工具窗口、操作和设置。
import uvicorn

from fastapi.templating import Jinja2Templates
import cv2

from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import StreamingResponse #视频流

import threading

app = FastAPI( title="摄像头流接口",
    description="这是一个打开默认摄像头 流地址http://127.0.0.1:端口/video_feed/1",
    version="1.0.0")
cap = None
isImg = False
imgMean = 0


# 配置允许域名
origins = ["http://localhost","https://localhost","http://localhost:8000","http://localhost:8080",]
# 配置允许域名列表、允许方法、请求头、cookie等
app.add_middleware(CORSMiddleware,allow_origins=origins,allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)

# 2.将静态资源的 URL 挂载到指定路径
app.mount("/static", StaticFiles(directory="E:\\Code\\C++\\Examples\\photo"), name="static")




#渲染HTML模版 默认html模版目录
templates = Jinja2Templates(directory="templates")

def print_hi(name):
    # 在下面的代码行中使用断点来调试脚本。
    print(f'Hi, {name}')  # 按 Ctrl+F8 切换断点。



@app.get("/video_feed/{rotate}",description='获取监控视频流，示例&#60;&#105;&#109;&#103;&#32;&#115;&#114;&#99;&#61;&#34;&#104;&#116;&#116;&#112;&#58;&#47;&#47;&#49;&#50;&#55;&#46;&#48;&#46;&#48;&#46;&#49;&#47;&#118;&#105;&#100;&#101;&#111;&#95;&#102;&#101;&#101;&#100;&#47;&#49;&#34;&#32;&#47;&#62;',tags=["获取监控视频流"])
async def video_feed(rotate: int = None):
    # global cap
    #
    # if cap == None:
    #     cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    #     video_close_self()

    #<img src="http://127.0.0.1/video_feed/1" />
    # 返回带有视频流的StreamingResponse
    return StreamingResponse(generate_frames(rotate), media_type="multipart/x-mixed-replace;boundary=frame")



@app.get("/video_close",description='不需要用的时候一定要关闭，关闭监控视频',tags=["关闭监控视频"])
async def video_close():
    video_close_self()
    return {"msg": "已关闭","code":1}

@app.get("/is_open_video",description='是否打开监控视频',tags=["是否打开监控视频"])
async def is_open_video():
    if(isImg):
        msg = "打开中"
    else:
        msg = "已关闭"
    return {"msg": msg,"code":1,"data":isImg,"imgMean":imgMean}


def video_close_self():
    cap.release()  # 关闭摄像头
    print("video_close_self")

def video_open_self():
    cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # 打开摄像头
    print("video_open_self")

# 用于生成视频流的函数
def generate_frames(rotate=None):
    # 替换为您的视频文件路径或摄像头输入
    global cap,isImg,imgMean



    if cap==None:
        cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
    else:
        if not cap.isOpened():
            print("重新再次打开摄像头")
            cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
        else:
            print("再次打开摄像头")
            video_close_self()
            cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)


    if not cap.isOpened():
        print("无法再次打开摄像头")
    else:
        print("摄像头再次打开")
        # fps = cap.get(cv2.CAP_PROP_FPS)
        # print("摄像头fps",fps)
        while True:
            success, frame = cap.read()
            if not success:
                print("没有视频帧")
                video_close_self()
                video_open_self()
                print("重启1")
                generate_frames(rotate)

                break
            # 使用OpenCV将帧编码为JPEG格式
            # cv2.imshow("frame",frame)

            # 翻转
            if(rotate!=None):
                frame = cv2.flip(frame, rotate)
            imgMean = frame.mean()
            if(imgMean<10):
                isImg = False
                video_close_self()
                video_open_self()
                print("重启2")
                generate_frames(rotate)
            else:
                isImg = True


            # 进行水平翻转
            # frame = cv2.flip(frame, 1)

            # 进行垂直翻转
            # frame = cv2.flip(frame, 0)

            # 进行水平和垂直翻转
            # frame = cv2.flip(frame, -1)


            ret, buffer = cv2.imencode('.jpg', frame)
            # print(frame.size)

            if not ret:
                break
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')


# 按装订区域中的绿色按钮以运行脚本。
if __name__ == '__main__':
    print_hi('video')
    uvicorn.run(app, host="0.0.0.0", port=3999)

# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助
